//
//  EPMPictureView.m
//  WeiBoByOC
//
//  Created by 马继鵬 on 17/4/4.
//  Copyright © 2017年 7TH. All rights reserved.
//

#import "EPMPictureView.h"
#import "EPMPictureCell.h"

@interface EPMPictureView()<UICollectionViewDelegate,UICollectionViewDataSource>

@end

@implementation EPMPictureView

- (instancetype)initWithFrame:(CGRect)frame {
    
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat margine = 5.0;
    CGFloat itemWH = (screenWidth - 2*margine - 2*10)/3;
    flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
    flowLayout.minimumLineSpacing = margine;
    flowLayout.minimumInteritemSpacing = margine;
    
    if (self = [super initWithFrame:frame collectionViewLayout:flowLayout]){
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    self.dataSource = self;
    self.delegate = self;
    [self registerClass:[EPMPictureCell class] forCellWithReuseIdentifier:@"cell"];
//    self.hidden = YES;
}

#pragma
#pragma-数据源方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
     self.hidden = !self.imgList.count;
    NSInteger count = self.imgList.count;
    if (count == 0 || count ==9){
        return count;
    }
    return count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    EPMPictureCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.item == _imgList.count){
        cell.img = nil;
        return  cell;
    }
    cell.img = _imgList[indexPath.item];
    cell.backgroundColor = [UIColor EPM_getRandomColor];
    cell.deleteBtnBlock = ^(){
        [self.imgList removeObjectAtIndex:indexPath.item];
        [self reloadData];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.item == self.imgList.count){
        if (self.addPictureBlock){
            self.addPictureBlock();
            return;
        }
    }
    
    
    
}

- (void)setImgList:(NSMutableArray<UIImage *> *)imgList
{
    _imgList = imgList;
    
   
    [self reloadData];
}



@end
